<?php
class ImageController extends Controller
{
	public function init()
	{
		parent::init();
		$this->cs->registerScriptFile('/js/lib/admin/image.js');
	}

	public function actionIndex()
	{
		$model = new Image();
		if ($this->getParam('Image')) {
			$model->attributes = $this->getParam('Image');
		}
		$this->render('index',array(
			'model'=>$model,
		));
	}

	public function actionAdd()
	{
		$model = new Image();
		if ($this->isPostRequest() && $this->getParam('Image')) {
			$model->attributes = $this->getParam('Image');
			$model->image = CUploadedFile::getInstance($model,'image');
			$model->created_at = Yii::app()->format->dateHumanToNormal($model->created_at);
			$model->filename = $model->image->getName();
			$model->path = $model->calcDynamicPath();
			if ($model->save()) {
				$fileToSave = UPLOADS_PATH . $model->path . '/' . $model->filename;
				$model->image->saveAs($fileToSave);
				$this->redirect(array('/admin/image/index'));
			}
		}
		$this->render('add',array(
			'model'=>$model,
		));
	}

	public function actionUpdate()
	{
		$model = Image::model()->findByPk($this->getParam('id'));
		$model->created_at = Yii::app()->format->dateNormalToHuman($model->created_at);
		if ($this->isPostRequest() && $this->getParam('Image')) {
			$model->attributes = $this->getParam('Image');
			$model->created_at = Yii::app()->format->dateHumanToNormal($model->created_at);
			if ($model->save()) {
				$this->redirect(array('/admin/image/index'));
			}
		}
		$this->render('edit',array(
			'model'=>$model,
		));
	}

	public function actionDelete()
	{
		if ($id = (int) $this->getParam('id')) {
			Image::model()->deleteByPk($id);
		}
	}

	public function actionDeleteItems()
	{
		if ($ids = (array) $this->getParam('ids')) {
			Image::model()->deleteAllByIds($ids);
		}
	}

}
